package com.jwgf.Half485.modbusthreadpool;

import com.jwgf.comlibrary.Half485Manager;

import java.util.concurrent.Callable;

public class ModbusCallable implements Callable<ModbusData> {
    private static final int REPEAT_TIME = 2;
    private byte[] send;

    public ModbusCallable(byte[] send) {
        this.send = send;
    }

    @Override
    public ModbusData call() throws Exception {
        if (send != null) {
            for (int i = 0; i < REPEAT_TIME; ++i) {
                Half485Manager.getInstance().write1(send);
                byte[] recv = Half485Manager.getInstance().read1(50);
                int len = ModbusUtils.getReturnByteLen(send);
                if (recv != null && recv.length == len) {
                    int crc = ModbusUtils.crcCheck(recv, recv.length - 2);
                    byte crcHi = (byte) ((crc >> 8) & 0xff);
                    byte crcLo = (byte) (crc & 0xff);
                    if ((crcHi == recv[recv.length - 2]) && (crcLo == recv[recv.length - 1])) {
                        //通讯成功
                        ModbusData modbusData = new ModbusData();
                        modbusData.send = send;
                        modbusData.recv = recv;
                        modbusData.isDone = true;
                        return modbusData;
                    } else{
                        //失败
                        continue;
                    }

                } else {
                    // 失败
                    continue;
                }
            }
            // 通讯失败
            ModbusData modbusData = new ModbusData();
            modbusData.send = send;
            modbusData.isDone = false;
            return modbusData;
        }
        return null;
    }
}
